<template>
  <div class="van-uploader-content">
		<van-uploader
			v-show="false"
			:modelValue="modelValue"
		/>
    <div @click="choiceFile()" v-if="modelValue.length < maxCount && !props.readonly">
      <slot>
        <div :class="{'upload-btn': true, 'upload-btn_disabled': props.disabled}">
          <van-icon name="plus" />
          <span>上传文件</span>
        </div>
      </slot>
    </div>
    <div class="tip">
      {{ props.accept.length ? '请选择' + props.accept.join('、') + '文件，' : '' }}
      {{ '单个文件大小不可超过' + props.maxSize + 'MB，' }}
      {{ '最多上传' + props.maxCount + '个文件' }}
    </div>
    <div class="pic-list">
      <div v-for="(item, index) in props.modelValue" :key="index" class="file-box">
        <p class="file-name" :href="item.url">{{ getFileName(item.url) }}</p>
        <van-icon name="close" v-if="!props.readonly" size="18" @click="deleteFile(item)"></van-icon>
      </div>
    </div>
    <input ref="inputTarget" type="file" :multiple="props.maxCount > 1" style="display: none" @change="changeFile" />
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits } from 'vue'
import { Toast } from 'vant'
import { imgUpload } from '@/service/village'

const props = defineProps({
  accept: {
    type: Array,
    default: () => []
  },
	modelValue: {
    type: Array,
    default: () => []
  },
  maxCount: {
    type: Number,
    default: 10
  },
  maxSize: {
    type: Number,
    default: 40
  },
  readonly: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:modelValue'])
const inputTarget = ref(null)

const choiceFile = () => {
  if (props.readonly || props.disabled) return
  inputTarget.value.value = ''
  inputTarget.value.click()
}


const dealFile = async(files) => {
  let maxLength = props.maxCount - props.modelValue.length || 0
  for (let i = 0; i < maxLength; i++) {
		let file = files[i]
		if (!file) {
			break
		}
		if (file.size > props.maxSize * 1024 * 1024) {
			Toast('选择文件大小不可超过40MB')
			break
		}
		uploadImage(file)
	}
}

const uploadImage = async (file) => {
	try {
		const form = new FormData()
		form.append('File', file)
		const result = await imgUpload(form)
		if (result) {
			emits('update:modelValue', [
				...props.modelValue,
				{
					url: result,
					status: 'done',
				}
			])
		}
	} catch (err) {
		Toast('上传失败，请稍后重试。')
	}
}

const changeFile = () => {
  let fileInputEle = inputTarget.value
  let files = []
  if (fileInputEle.files && fileInputEle.files.length) {
    if (props.maxCount > 1) {
      files = fileInputEle.files
    } else {
      files = fileInputEle.files[0]
    }
  }
  dealFile(files)
}

const deleteFile = (e) => {
	const newArr = [...props.modelValue]?.filter(item => item !== e)
	emits('update:modelValue', newArr)
}

const getFileName = (url) => {
	try {
		let _url = new URL(url)
		let fileName = _url.pathname.slice(_url.pathname.lastIndexOf('/') + 1)
		fileName = decodeURIComponent(fileName)
		let newFileName = fileName.slice(0, fileName.lastIndexOf('-')) + '.' + fileName.slice(fileName.lastIndexOf('.') + 1)
		return newFileName
	} catch (e) {
		//
	}
}
</script>
<style scoped lang="less">
.van-uploader-content {
  background: #fff;
  width: 100%;
  .upload-btn {
		background: var(--van-primary-color);
    height: 56px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    padding: 0 22px;
    color: #fff;
    font-size: 28px;
    border-radius: 28px;
    margin: 12px 0;
    &.upload-btn_disabled {
      opacity: 0.6;
    }
  }
  .tip {
    font-size: 24px;
		line-height: 40px;
    color: #aaa;
    margin: 8px 0;
  }
  .file-box {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 24px;
    .file-name {
      flex: 1;
      word-break: break-all;
      color: #1890ff;
      white-space:nowrap;
      overflow:hidden;
      text-overflow:ellipsis;
    }
    i {
      margin-left: 8px;
    }
  }
}
</style>
